package net.sk.dc;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import dao.hb.ODevice;

import net.bat.util.Cfg;
import net.sk.pt.IKeeper;
import net.sk.pt.IProvider;
import net.sk.pt.State;
import net.sk.pt.StateUtil;
import net.sk.web.StateCenter;

public class IDCCenter {
	
	static public final String IDC_PRE = "net.sk.dc.IDC_";
	HashMap<Integer,IDC> map_idc;
	HashMap<String,Class<?>> map_idc_cls;
	
	public void registerIDC() throws ClassNotFoundException, InstantiationException, IllegalAccessException{		
		map_idc = new HashMap<Integer,IDC>();
		map_idc_cls = new HashMap<String,Class<?>>();
		String[] idcNames = new String[]{"Cam","CAM_Robot","GTI_Robot","Robot"};
		for(int i=0; i<idcNames.length; i++){
			map_idc_cls.put(idcNames[i], Class.forName(IDC_PRE+idcNames[i]));
		}
	}
	public Class<?> getIDCCls(String cn){
		return map_idc_cls.get(cn);
	}
	public IDC getIDC(Integer deviceId){
		return map_idc.get(deviceId);
	}
	public void clearIDC(){
		Iterator<Entry<Integer, IDC>> iter = map_idc.entrySet().iterator(); 
		while (iter.hasNext()) { 
		    Map.Entry<Integer, IDC> entry =  iter.next(); 
		    IDC val = entry.getValue(); 
		    if(val!=null)
		    	val.close();
		} 	
		map_idc.clear();		
	}
	public void buildIDC(){
		clearIDC();
		IProvider pr = Cfg.getSC().getProvider(StateCenter.PR_PR_DAO);
		IKeeper kpr = pr.getKeeper();
		HashMap<Object,State> smap_divice_type = kpr.getStatesByCn(StateCenter.DAO_DeviceType);
		if(smap_divice_type==null){
			return;
		}
		HashMap<Object,State> smap_device = kpr.getStatesByCn(StateCenter.DAO_DEVICE);
		if(smap_device==null){
			return;
		}
		Iterator<Entry<Object,State>> iter = smap_device.entrySet().iterator(); 
		while (iter.hasNext()) { 
			 Map.Entry<Object,State> entry =  iter.next(); 
			 State val = entry.getValue();
			 String mk = StateCenter.DAO_DeviceType + StateUtil.keyJoin+ val.getItems().get("mid");
			 State val_type = smap_divice_type.get(mk);
			 if(val_type==null)
				 continue;
			 Object smode = val_type.getItems().get("smode");
			 Class<?> idc = getIDCCls((String)smode);
			 if(idc==null)
				 continue;
			 IDC dc;
			try {
				dc = (IDC)idc.newInstance();
				 ODevice od = (ODevice)StateUtil.getso(val);
				 dc.open(od);
				 map_idc.put(od.getId(), dc);
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
		}
		
	}

}
